<template>
  <div class="w-badge-wrap">
    <slot></slot>
    <transition :name="`${transition}`">
      <div
        class="w-badge"
        v-if="modelValue"
        :class="classes"
        :style="styles"
        aria-atomic="true"
        aria-label="Badge"
        aria-live="polite"
        role="status"
      >
        <slot v-if="!dot" name="badge">{{
          modelValue === true ? "" : modelValue || ""
        }}</slot>
      </div>
    </transition>
  </div>
</template>

<script>
import { computed } from "vue";
export default {
  name: "w-badge",

  props: {
    modelValue: { default: true },
    xs: { type: Boolean },
    sm: { type: Boolean },
    md: { type: Boolean },
    lg: { type: Boolean },
    xl: { type: Boolean },
    top: { type: Boolean },
    left: { type: Boolean },
    right: { type: Boolean },
    bottom: { type: Boolean },
    overlap: { type: Boolean },
    inline: { type: Boolean },
    color: { type: String },
    size: { type: [Number, String] },
    bgColor: { type: String, default: "primary" },
    dark: { type: Boolean },
    badgeClass: { type: String },
    outline: { type: Boolean },
    shadow: { type: Boolean },
    dot: { type: Boolean },
    round: { type: Boolean },
    transition: { type: String, default: "fade" }
  },

  emits: [],
  setup(props, { slots }) {
    const forcedSize = computed(() => {
      return (
        props.size && (!isNaN(props.size) ? `${props.size}px` : props.size)
      );
    });
    const presetSize = computed(() => {
      return (
        (props.xs && "xs") ||
        (props.sm && "sm") ||
        (props.md && "md") ||
        (props.lg && "lg") ||
        (props.xl && "xl") ||
        "md"
      );
    });
    const position = computed(() => {
      return [
        (props.top && "top") || (props.bottom && "bottom") || "top",
        (props.left && "left") || (props.right && "right") || "right"
      ];
    });
    const classes = computed(() => {
      const slotText =
        slots.badge &&
        slots
          .badge()
          .map(item => item.children)
          .join("");
      return {
        [props.color]: props.color,
        [`${props.bgColor}--bg`]: props.bgColor,
        [props.badgeClass]: props.badgeClass || null,
        "w-badge--round":
          props.round || (slotText || props.modelValue + "" || "").length < 2,
        "w-badge--dark": props.dark && !props.outline,
        "w-badge--outline": props.outline,
        "w-badge--inline": props.inline,
        "w-badge--shadow": props.shadow,
        "w-badge--overlap": props.overlap,
        "w-badge--dot": props.dot,
        [`size--${props.presetSize}`]: props.presetSize && !props.forcedSize,
        [`w-badge--${position.value.join(" w-badge--")}`]: true
      };
    });
    const styles = computed(() => {
      return props.forcedSize && `font-size: ${props.forcedSize}`;
    });
    return {
      forcedSize,
      presetSize,
      position,
      classes,
      styles
    };
  }
};
</script>